package cn.itsource.hrm.feign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class DefaultOAuth2FeignRequestInterceptor implements RequestInterceptor {

    public static final String HEAD_TOKEN = "Authorization";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取之前请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        //获取请求中的token
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader(HEAD_TOKEN);
        if(StringUtils.isNotEmpty(token)){
            //把token放到feign的请求头中
            requestTemplate.header("Authorization",token);
        }
   }
}